package com.gl.sass.mq.producer.retry;

import lombok.Data;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

import org.apache.rocketmq.common.message.Message;

/**
 * 	重试消息体
 * @author xiehong
 *
 */
@Data
public class RetryMessage implements Delayed {

    /**
     * 	延迟时间间隔
     * 	从0次到4次
     * 	单位是秒
     */
    private static final int[] DELAY_TIME = {5, 30, 300, 1800};

    /**
     * 	mq消息体
     */
    private Message msg;

    /**
     * 	当前已经重试的次数
     */
    private int retryTimes;

    /**
     * 	下次触发重试的时间
     */
    private long nextRetryTime;

    public RetryMessage(Message msg) {
        this.msg = msg;
        this.retryTimes = 0;
        retryAgain();
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(nextRetryTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return this.getDelay(TimeUnit.MILLISECONDS) <= o.getDelay(TimeUnit.MILLISECONDS) ? -1 : 1;
    }

    public RetryMessage retryAgain() {
        this.retryTimes++;
        int index = retryTimes;
        if (retryTimes >= DELAY_TIME.length) {
            index = DELAY_TIME.length;
        }
        this.nextRetryTime = System.currentTimeMillis() + DELAY_TIME[index - 1] * 1000L;
        return this;
    }

    public String toPrint() {
        return "RetryMessage{" + "msg=" + msg + ", retryTimes=" + retryTimes + ", nextRetryTime=" + nextRetryTime + '}';
    }
}
